(function () {
  'use strict';

  // PasswordValidator service used for testing the password strength
  angular
    .module('users.services')
    .factory('PasswordValidator', PasswordValidator);

  PasswordValidator.$inject = ['$window'];

  function PasswordValidator($window) {
    var owaspPasswordStrengthTest = $window.owaspPasswordStrengthTest;

    var originalOptionCount = owaspPasswordStrengthTest.configs.minOptionalTestsToPass;
    var newOptionCount = 2;
    owaspPasswordStrengthTest.config( {
      minOptionalTestsToPass: newOptionCount,  // Must contains lower char and number
      minLength: 8
    });

    var service = {
      getResult: getResult,
      getPopoverMsg: getPopoverMsg
    };

    return service;

    function getResult(password) {
      var result = owaspPasswordStrengthTest.test(password);
      // remove: The password must contain at least one uppercase letter.
      // remove: The password must contain at least one special character.

      if (result.errors.length) {
        var rmErrs = [
          'The password must contain at least one special character.',
          'The password must contain at least one uppercase letter.'
        ];
        rmErrs.forEach(function (err) {
          var index = result.errors.indexOf(err);
          if(index != -1) {
            result.errors.splice(index, 1);
          }
        })
      }

      return result;
    }

    function getPopoverMsg() {
      var popoverMsg = 'Please enter a passphrase or password with ' + owaspPasswordStrengthTest.configs.minLength + ' or more characters and numbers.';

      return popoverMsg;
    }
  }

}());
